package vip.aster.system.controller;

import cn.hutool.core.io.IoUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import vip.aster.common.exception.BusinessException;
import vip.aster.common.utils.ResultInfo;
import vip.aster.system.entity.SysLogOperate;
import vip.aster.system.entity.SysOrg;
import vip.aster.system.entity.SysUser;
import vip.aster.system.service.TestService;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * TestController
 *
 * @author Aster
 * @since 2024/3/1 14:18
 */
@AllArgsConstructor
@RequestMapping("/test")
@RestController
public class TestController {
    private TestService testService;

    @GetMapping("/zip")
    public void zip(HttpServletResponse response) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        String content = "123";
        String path = "main/java/domain/post.java";
        try {
            // 添加到zip
            zip.putNextEntry(new ZipEntry(path));
            IOUtils.write(content, zip, "UTF-8");
//            IOUtils.closeQuietly(content);
            zip.flush();
            zip.closeEntry();
        } catch (IOException e) {
            throw new BusinessException("模板写入失败：" + path, e);
        }
        IOUtils.closeQuietly(zip);

        // zip压缩包数据
        byte[] data = outputStream.toByteArray();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"aster.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), false, data);
    }

    @GetMapping("/permission/dept")
    public ResultInfo<List<SysOrg>> orgList() {
        return ResultInfo.success(testService.orgList());
    }

    @GetMapping("/permission/user")
    public ResultInfo<List<SysLogOperate>> operateList() {
        return ResultInfo.success(testService.operateList());
    }

    @GetMapping("/permission/deptOrUser")
    public ResultInfo<List<SysUser>> userList() {
        return ResultInfo.success(testService.userList());
    }

    @GetMapping("/permission/deptAndUser")
    public ResultInfo<String> updateUser(@RequestParam String email) {
        testService.updateUser(email);
        return ResultInfo.success();
    }

}
